var map;
var centerLatitude = 22.159427;
var centerLongitude = 38.161011;
var startZoom = 8;
var bottomLeft1 = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(5,50));
var bottomLeft2 = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(70,10));

var verticalShift = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(5,245));
var horizontalShift = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(415,5));
var standard2= new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(15,5));

var horizontalVerticalShift = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(415,245));
var horizontalVerticalNoShift = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(15,245));

var mapControl3d = new GLargeMapControl3D();
var menuMapType = new GMenuMapTypeControl();

function addMarker(longitude, latitude, description) {
  var marker = new GMarker(new GLatLng(latitude, longitude));

  GEvent.addListener(marker, 'click',
    function() {
      marker.openInfoWindowHtml(description);
    }
    );

  map.addOverlay(marker);
}

/* [listing 6-10] */
function windowHeight() {
  // Standard browsers (Mozilla, Safari, etc.)
  if (self.innerHeight)
    return self.innerHeight;
  // IE 6
  if (document.documentElement && document.documentElement.clientHeight)
    return document.documentElement.clientHeight;
  // IE 5
  if (document.body)
    return document.body.clientHeight;
  // Just in case.
  return 0;
}

function handleResize() {
  var height = windowHeight() - document.getElementById('topmenu').offsetHeight - 30;
  var widthx = document.getElementById('topmenu').offsetWidth - 400;
  document.getElementById('map').style.height = height + 'px';
  document.getElementById('sidebar').style.height = height + 'px';
  document.getElementById('statistics').style.width = widthx + 'px';
}
/* [listing 6-10 end] */

function changeBodyClass(from, to) {
  document.body.className = document.body.className.replace(from, to);
  return false;
}

function init() {
  //document.getElementById('button-sidebar-hide').onclick = function() { return changeBodyClass('sidebar-right', 'nosidebar'); };
  //document.getElementById('button-sidebar-show').onclick = function() { return changeBodyClass('nosidebar', 'sidebar-right'); };
  handleResize();

        
  /* [listing 6-10 end] */
	
  map = new GMap2(document.getElementById("map"));
  map.setMapType(G_SATELLITE_MAP);
  map.addControl(mapControl3d);
  map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom);
  map.addControl(menuMapType, horizontalShift);

  //Update the Vetical Control
  GEvent.addListener(map, "updateVerticalControlsDown", function() {
    map.removeControl(mapControl3d);
    map.addControl(mapControl3d, verticalShift);
  });

  GEvent.addListener(map, "updateVerticalControlsUp", function() {
    map.removeControl(mapControl3d);
    map.addControl(mapControl3d);
  });

  //Update the Horizontal Control
  GEvent.addListener(map, "updateHorizontalControlsDown", function() {
    map.removeControl(menuMapType);
    map.addControl(menuMapType, horizontalShift);
  });

  GEvent.addListener(map, "updateHorizontalControlsUp", function() {
    map.removeControl(menuMapType);
    map.addControl(menuMapType,standard2);
  });

  //Update the HorizontalVertical Control
  GEvent.addListener(map, "updateHorizontalVerticalControlsDown", function() {
    map.removeControl(menuMapType);
    map.addControl(menuMapType, horizontalVerticalShift);
  });

  GEvent.addListener(map, "updateHorizontalVerticalControlsUp", function() {
    map.removeControl(menuMapType);
    map.addControl(menuMapType,horizontalVerticalNoShift);
  });

  //Update the HorizontalVertical :S Control
  GEvent.addListener(map, "updateHorizontalANDVerticalControlsDown", function() {
    map.removeControl(menuMapType);
    map.addControl(menuMapType, horizontalVerticalShift);
  });

  GEvent.addListener(map, "updateNoHorizontalANDVerticalControlsUp", function() {
    map.removeControl(menuMapType);
    map.addControl(menuMapType,horizontalVerticalNoShift);
  });
  /*
	for(id in markers) {
		addMarker(markers[id].longitude, markers[id].latitude, markers[id].name);
	}
        */

  map.enableScrollWheelZoom();
}

function updatePositionVerticalControl(toggledVertical, toggledHorizontal){
  (toggledVertical)?GEvent.trigger(map, "updateVerticalControlsDown"):GEvent.trigger(map, "updateVerticalControlsUp");
  if(toggledVertical){
    (toggledHorizontal)?GEvent.trigger(map, "updateHorizontalVerticalControlsDown"):GEvent.trigger(map, "updateHorizontalVerticalControlsUp");
  }else{
    (toggledHorizontal)?GEvent.trigger(map, "updateHorizontalControlsDown"):GEvent.trigger(map, "updateHorizontalControlsUp");
  }
}

function updatePositionHorizontalControl(toggledVertical, toggledHorizontal){
  if(!toggledVertical){
    (toggledHorizontal)?GEvent.trigger(map, "updateHorizontalControlsDown"):GEvent.trigger(map, "updateHorizontalControlsUp");
  }else{
    (toggledHorizontal)?GEvent.trigger(map, "updateHorizontalANDVerticalControlsDown"):GEvent.trigger(map, "updateNoHorizontalANDVerticalControlsUp");
  }
}
/* [listing 6-10] */
window.onresize = handleResize;
/* [listing 6-10 end] */
window.onload = init;

var invertebrate = new GIcon(); 
invertebrate.image = '../../images/mapicons/Invertebrate.png';
invertebrate.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
invertebrate.iconSize = new GSize(28, 36);
//invertebrate.shadowSize = new GSize(22, 20);
invertebrate.iconAnchor = new GPoint(6, 20);
invertebrate.infoWindowAnchor = new GPoint(5, 1);

var customIcons = [];
customIcons["invertebrate"] = invertebrate;

//Define xmlGMapData object

function XMLGmapData(){
  var id;
  var family;
  var icon;
  var genusSpecies;
  var quantity;
  var depth;
  var zone;
  var latitude;
  var longitude;
  var point;
  var temperature;
  var salinity;
}

function createGMarker(xmlGmapData) {
  /* 
  if(cat_id == 1)
      var record = new GMarker(point, customIcons["microbes"]);
  else if(cat_id == 2)
      var record = new GMarker(point, customIcons["primaryproducer"]);            
  else if(cat_id == 3)
      var record = new GMarker(point, customIcons["invertebrate"]);
  */

  var record = new GMarker(
    xmlGmapData.point,  {
      icon: customIcons["invertebrate"]
    });

  var html = "<b>" + xmlGmapData.genusSpecies + "</b> <br/>" + 
  "zone: " + xmlGmapData.zone + "<br/>" +
  "deep: " + xmlGmapData.depth + " m <br/>" +
  "quantity: " + xmlGmapData.quantity;

  GEvent.addListener(record, 'click', function() {
    record.openInfoWindowHtml(html);

  });
  return record;
}

var markerClusterer= null;
function generateGMarks(fileUrl){
  //selectedMarksManager = new GMarkerManager({map: map});
  
  $.ajax({
    type: "GET",
    url: fileUrl,
    dataType: "xml",
    success: function(xml) {
      var latitudeAvg = 0;
      var longitudeAvg = 0;
      var i=0;
      var markers = Array();
      $(xml).find('rbis').each(function(){


        $(this).find('species').each(function(){
          var id = $(this).attr('id');
          var family;
          var icon;
          var genusSpecies;
          var quantity;
          var depth;
          var zone;

          $(this).children('name').each(function(){
            family = $(this).find('family').text();
            genusSpecies = $(this).find('genusSpecies').text();
          });

          icon = $(this).children('icon').text();


          $(this).find('record').each(function(){
            quantity = $(this).find('quantity').text();
            depth = $(this).find('depth').text();
            zone = $(this).find('zone').text();

            $(this).children('station').each(function(){
              var xmlGmapData = new XMLGmapData;
              xmlGmapData.id = id;
              xmlGmapData.family = family;
              xmlGmapData.icon = icon;
              xmlGmapData.genusSpecies = genusSpecies;
              xmlGmapData.quantity = parseFloat(quantity);
              xmlGmapData.depth = depth;
              xmlGmapData.zone = zone;
              xmlGmapData.latitude = parseFloat($(this).find('latitude').text());

              xmlGmapData.longitude = parseFloat($(this).find('longitude').text());

              xmlGmapData.temperature = $(this).find('temperature').text();
              xmlGmapData.salinity = $(this).find('salinity').text();

              //to calculate mean
              if (!isNaN(xmlGmapData.longitude) ){
                if (!isNaN(xmlGmapData.latitude) ){

                  longitudeAvg+= xmlGmapData.longitude;
                  latitudeAvg+= xmlGmapData.latitude;
                  xmlGmapData.point = new GLatLng(xmlGmapData.latitude, xmlGmapData.longitude);
                  //var record = createRecord(zone, deep, quantity, point, name, cat_id);
                  var marker = new createGMarker(xmlGmapData);
                  marker.data = xmlGmapData;
                  markers.push(marker);
                }
              }
            });//endof each station
          });//endof each record
        });//endof each species
      });// finished each function for each species
        
      latitudeAvg /= markers.length;
      longitudeAvg /= markers.length;
	  
      map.clearOverlays();
      if(markerClusterer!=null)markerClusterer.clearMarkers();
      markerClusterer = new MarkerClusterer(map, markers, {
        maxZoom: 25,
        gridSize: 40,
        clicked: clusterClicked
      });
			
    /*
      markManager = new GMarkerManager(map);
      markManager.addMarkers(markers, 1);
      markManager.refresh();
	  */

    //map.setCenter(new GLatLng(latitudeAvg, longitudeAvg), 8);
    }
  }); //Finished the creation of markers and XML parsing
//

//selectedMarksManager.refresh();

}

//@todo have to improve the way this arguments are passed
function clusterClicked(markers, latlng){

  var i;
  var nameSpecies = new Array();
  for (i=0; i<markers.length; i++){
    nameSpecies[i] = markers[i].data.genusSpecies;
  }
  nameSpecies = nameSpecies.unique();
  var countSpecies = new Array(nameSpecies.length);
  for(i=0; i<countSpecies.length; i++){
    countSpecies[i]=0;
  }

  var j;
  for(i=0; i<markers.length; i++){
    for(j=0; j<nameSpecies.length; j++){
      if(markers[i].data.genusSpecies==nameSpecies[j]){
        countSpecies[j] += markers[i].data.quantity;
        break;
      }
    }
  }
  
  //@todo remove this hardcoded tag and get it from database (when transformed to CMS)
  var html = "<b>Species</b><br />";
  
  //change this calculation according to the properties selected, also for scalability when to CMS
  var totalSum=0;
  for(i=0; i<nameSpecies.length; i++){
    html+=nameSpecies[i]+": "+ countSpecies[i]+"<br />";
    totalSum+=countSpecies[i];
  }
  html += "<hr />Total: " + totalSum;

  map.openInfoWindow(latlng, html);
}